﻿//Copyright (c) Microsoft Corporation.  All rights reserved.

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Threading;

namespace Microsoft.Ted.Wacel.TableStorage
{
    public class CloudSyncRoot
    {
        private CloudBlobClient mClient;
        private CloudBlobContainer mContainer;
        public CloudSyncRoot(string connectionString, string name)
        {
            CloudStorageAccount account = CloudStorageAccount.Parse(connectionString);
            mClient = account.CreateCloudBlobClient();

            mContainer = mClient.GetContainerReference(name);
            mContainer.CreateIfNotExists();
            var permissions = mContainer.GetPermissions();
            permissions.PublicAccess = BlobContainerPublicAccessType.Container;
            mContainer.SetPermissions(permissions);
        }
        public string Accquire(string key, TimeSpan timespan)
        {
            while (true)
            {
                    var blob = mContainer.GetBlockBlobReference(key);
                    if (blob.Exists())
                    {
                        try
                        {
                            return blob.AcquireLease(timespan, Guid.NewGuid().ToString());
                        }
                        catch (StorageException)
                        {
                            Thread.Sleep(100);
                        }
                    }
                    else
                    {
                        try
                        {
                            blob.UploadText("L");
                        }
                        catch
                        {

                        }
                    }
               
            }
        }
        public void Release(string key, string leaseId)
        {
            var blob = mContainer.GetBlockBlobReference(key);
            blob.ReleaseLease(new AccessCondition { LeaseId = leaseId });
        }
    }
}
